import PageTab, { AudTabPage } from '@/components/PageTab';
import RightContent from '@/components/RightContent';
import WebFrame from '@/pages/web_frame';
import { loadMessages, locale } from 'devextreme/localization';
import enMessages from 'devextreme/localization/messages/en.json';
import zhMessages from 'devextreme/localization/messages/zh.json';
import Dexie from 'dexie';
import { lazy } from 'react';
import type { RunTimeLayoutConfig } from 'umi';
import { getLocale, history } from 'umi';
import type { InitState } from './layouts';
import { getRunTimeLayoutConfig, getSysName, loginPath } from './layouts';
import getRTS, { getRTSMenus } from './layouts/runtimeSettings';
import { getCurrentZcbfInfo } from './services/cpasRequest';
import { isOpenFromPlatform, isRunInFrame } from './utils/env';
import { getAllRoutes } from './router';
let menuJson: any[] = [];
/** 获取用户信息比较慢的时候会展示一个 loading */
// export const initialStateConfig = {
//   loading: <PageLoading />,
// };

// window.setup = (locale) => {
//   console.log('setup');
//   // const { initialState, loading, error, refresh, setInitialState } = useModel('@@initialState');
//   // setInitialState((state) => {
//   //   return { ...state, abc: 1 };
//   // });
//   setLocale(locale, true);
// };

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */

export async function getInitialState(): Promise<InitState> {
  devLocale();
  await Dexie.delete('cpasCacheDb');
  const rts = await getRTS();
  const menuJsonData: any[] = await getRTSMenus();

  // 如果是登录页面，不执行
  const pathName = window.location.pathname;
  const hash = window.location.hash;

  let curUser = null;
  let sessionCur = null;
  try {
    curUser = JSON.parse(window.localStorage?.getItem('cpasUserInfo') ?? '');
    sessionCur = JSON.parse(window.sessionStorage?.electronParams).params;
  } catch (error) {
    console.log('error 获取storage用户信息', error);
  }
  const { data: curDataPart } = await getCurrentZcbfInfo({ zcbfID: sessionCur?.ZcbfID });

  // let curPart: any = {}
  const curPart = {
    ...curDataPart,
    dbname: curDataPart.DBName,
    zcbfid: curDataPart.ZcbfID,
  };

  // 修改本地session的存值
  const electronSession = {
    params: curPart,
    session: 'persist:local',
  };
  window.sessionStorage.setItem('electronParams', JSON.stringify(electronSession));

  const commonInitParams = {
    settings: rts,
    curUser: curUser,
    menuJson: menuJsonData,
    curPart: curPart,
  };

  //electron平台
  if (window.electronComponents) {
    if (localStorage.getItem('cpasMainToken')) {
      const sysName = getSysName(pathName);
      if (!hash) history.push('/home');
      return {
        ...commonInitParams,
        sysName,
      };
    }
  }
  if (!hash) history.push('/home');
  if (pathName !== loginPath) {
    const sysName = getSysName(pathName);
    return {
      ...commonInitParams,
      sysName,
    };
  }
  return {
    ...commonInitParams,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }: any) => {
  const layoutConfig = getRunTimeLayoutConfig(initialState);
  console.log(layoutConfig, 'layoutConfig');
  const inFrameLayout = isRunInFrame ? { hide: true, headerHeight: 0 } : {};
  const inPlatformLayout = isOpenFromPlatform ? { hide: true, headerHeight: 0 } : {};
  return {
    ...inFrameLayout,
    ...layoutConfig,
    // siderWidth: typeof SIDER_WIDTH !== 'undefined' ? SIDER_WIDTH : 208,
    siderWidth: initialState && initialState.siderWidth === 0 ? 0 : 228,
    // siderWidth: 0,
    headerHeight: 0,
    childrenRender: initialState && initialState?.curUser ? PageTab : undefined,
    rightContentRender: () => <RightContent />,
    // footerRender: () => <Footer />,
    // links: layoutLinks(),
    // menuHeaderRender: undefined,
    menuHeaderRender: false,
    // 自定义 403 页面
    unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
    ...inPlatformLayout,
    navTheme: 'light',
  };
};

// 后端数据请求配置，具体看 './services/index.ts'
// export const request: RequestConfig = {
//   requestInterceptors: [reqInterceptor as any],
//   // responseInterceptors: [resInterceptor],
//   errorHandler: errorHandler,
// };

function getPathAfterNthSlash(path: string, n: number) {
  const parts = path.split('/');
  if (n >= parts.length - 1) {
    return ''; // 如果 n 大于等于斜杠数减一，则返回空字符串
  }
  return parts.slice(n + 1).join('/');
}

async function parseMenuRoute(mainRoute: any) {
  const initPageByMenuJson = (menuData: any, level = 0): void => {
    for (let i = 0; i < menuData.length; i++) {
      const menu = menuData[i];
      const icon = menu.icon;
      const appName = menu.label;
      const appType = menu.type;
      const hiddenMenu = menu?.hiddenMenu ? menu?.hiddenMenu : false;
      const lastAppName = menu.path.substring(menu.path.lastIndexOf('/') + 1);
      if (menu.children) {
        if (!hiddenMenu) {
          mainRoute.unshift({
            key: menu.path,
            path: menu.path,
            name: appName,
            icon: icon,
            closable: lastAppName !== 'home',
          });
        }
        initPageByMenuJson(menu.children, level + 1);
      } else {
        // 动态路由根据层级来进行解析, 例如: { a:{b:{},c:{},children:{d:{},:e{}}}}  ,  d的路径就是截取 level 个 / 后面的路径
        // 解决一个文件夹配置多个页面
        let currentLevelAppName = getPathAfterNthSlash(menu.path, level);

        // 查找 `?` 的位置
        const startIndex = currentLevelAppName.indexOf('?');

        // 截取 `?` 后面的所有内容
        const queryString =
          startIndex === -1 ? '' : '?' + currentLevelAppName.substring(startIndex + 1);

        if (startIndex > -1) {
          currentLevelAppName = currentLevelAppName.substring(0, startIndex);
        }

        // console.log(menu);
        if (appType === 'component') {
          if (!hiddenMenu) {
            mainRoute.unshift({
              key: menu.path,
              path: menu.path,
              name: appName,
              icon: icon,
              closable: lastAppName !== 'home',
              // component: require(`@/pages/${app}/index`).default,
              component: lazy(() => import(`@/pages/${currentLevelAppName}/index${queryString}`)),
            });
          }
        } else if (appType === 'web') {
          if (!hiddenMenu) {
            mainRoute.unshift({
              key: menu.path,
              path: menu.path,
              name: appName,
              icon: icon,
              closable: true,
              component: <WebFrame url={menu.path} />,
            });
          }
        }
      }
    }
  };
  if (menuJson.length) {
    initPageByMenuJson(menuJson);
    console.log('initPageByMenuJson success');
  }
}

export const modifyClientRenderOpts = (context: any) => {
  const h = context.history;
  const originPush = h.push;
  const originReplace = h.replace;
  h.push = (...args: any) => {
    // args[0] = base + args[0]
    originPush.apply(h, args);
  };
  h.replace = (...args: any) => {
    originReplace.apply(h, args);
  };
  return context;
};

// export async function render(oldRender: any) {
//   menuJsonData = (await getRTSMenus()) as any;
//   oldRender();
// }

// 原 { routes } 报错，所以使用以下方法
export async function patchClientRoutes({ routes, routeComponents }: any) {
  const menuJson1 = (await getRTSMenus()) as any;
  menuJson = menuJson1;
  if (routes) {
    const allRoutes = getAllRoutes(menuJson);
    routes[0].routes.push(...allRoutes);
    await parseMenuRoute(routes[0].routes);
    AudTabPage.getInstance().setDynamicRoutes(menuJson);
    AudTabPage.getInstance().setRoutes(routes);
    AudTabPage.getInstance().initPages('audit');
  }
}

function devLocale() {
  // dev extreme local setting
  loadMessages(enMessages);
  loadMessages(zhMessages);
  const loca = getLocale();
  locale(loca?.slice(0, 2) || 'zh');
}